<?php // Submit Authored Article
require_once('./inc/inc.common.php');
$tmpl 			= new mvTemplate();
$title 			= '';
$keywords 		= '';
$articledata 	= '';
$description 	= '';

// Load article for editing
if(isset($_GET['fileid']) && $article = article::load($_GET['fileid'])){
	if($article->authorID == $_SESSION['user']->id || $_SESSION['user']->isAdmin){
		$title 			= $article->title;
		$keywords 		= $article->keywords;
		$articledata 	= $article->articleData;
		$tmpl->page_title('Edit Article');
	}else{
		mvError::userError('Permission denied', 'You do not have permission to edit this article.');
		$article = false;
	}
}else{
	$tmpl->page_title('Submit Article');
}

if(isset($_POST['submit'])){
	$aid = isset($_SESSION['user']) ? $_SESSION['user']->id : '';
	$title 			= $_POST['title'];
	$keywords 		= $_POST['keywords'];
	$articledata 	= $_POST['article'];
	$description 	= isset($_POST['description']) ? $_POST['description'] : '';
	$pass = true;
	// check User input
	if(strlen(trim($title)) == 0){
		$pass = false;
		mvError::userError('Missing Title', 'Please enter a title for your Article');
	}
	if(strlen(trim($articledata)) == 0){
		$pass = false;
		mvError::userError('Missing Article', 'Your article appears to be blank. please include some content.');
	}
	if(strlen(trim($keywords)) == 0){
		$pass = false;
		mvError::userError('Missing Keywords', 'You need to include some keywords in your article');
	}

	if($pass){
		$parent = (isset($_REQUEST['a']) && $_REQUEST['a'] != '') ? $_REQUEST['a'] : false;

		if(isset($article) && $article){
			$article->update($title, $articledata, $keywords);
		}else{
			$article = article::create($title, $aid, $articledata, $keywords, $parent);
		}

		if(!$article) trigger_error('There was an error adding your article.');

		if($article && isset($_FILES['upload']) && isset($_FILES['upload']['name']) && $_FILES['upload']['name'])
			$article->add_file($_FILES['upload']['tmp_name'], $_FILES['upload']['name'], $_FILES['upload']['type'], $description, $aid);
	}

	header('location: v.php?a=' . $article->id);
	die();
}

$tmpl->assign('title', $title);
$tmpl->assign('keywords', $keywords);
$tmpl->assign('articledata', $articledata);
$tmpl->assign('description', $description);
// grab the question if applicable
if(isset($_REQUEST['a'])  && $_REQUEST['a'] != '' && $a = article::load($_REQUEST['a']))
	$tmpl->assign('question', $a->articleData);

$tmpl->page_display('saa.tpl');
?>